package com.lxq.smartsign.smartattendance;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.lxq.smartsign.smartattendance.util.MonitorConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private RequestQueue queue;
    private SharedPreferences ipPreferences;
    private BluetoothAdapter bluetoothAdapter;
    //private TextView tipsV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏设置
        setTitle("员工考勤终端");
        requestPermissions();
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        //tipsV=findViewById(R.id.tips_view);
        queue= Volley.newRequestQueue(this);
        ipPreferences=getSharedPreferences("ip_config",MODE_PRIVATE);
        initData();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_login_setting:
                AlertDialog settingDialog=new AlertDialog.Builder(this).create();
                View dialogView=View.inflate(this,R.layout.dialog_network_setting,null);
                settingDialog.setTitle("设置服务器IP和端口");
                settingDialog.setView(dialogView);
                settingDialog.show();
                EditText ipV=dialogView.findViewById(R.id.server_ip);
                EditText portV=dialogView.findViewById(R.id.server_port);
                ipV.setText(MonitorConfig.IP);
                portV.setText(MonitorConfig.PORT);
                dialogView.findViewById(R.id.btn_test).setOnClickListener(v2->{
                    String url="http://"+ipV.getText().toString()+":"+portV.getText().toString()+"/monitor_test";
                    JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET,url,null, result->{
                        if (result.optInt("code")==0){
                            Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show();
                        }
                    },error -> Toast.makeText(this, "连接失败:"+error.getMessage(), Toast.LENGTH_SHORT).show());
                    queue.add(request);
                });
                dialogView.findViewById(R.id.btn_save_net_config).setOnClickListener(v3->{
                    ipPreferences.edit().putString("ip",ipV.getText().toString()).apply();
                    ipPreferences.edit().putString("port",portV.getText().toString()).apply();
                    MonitorConfig.setAddress(ipV.getText().toString(),portV.getText().toString());
                    settingDialog.dismiss();
                });

                break;
            case R.id.btn_login:
                String password=
                ((TextView)findViewById(R.id.edv_password)).getText().toString();
                JSONObject param=new JSONObject();
                String loginUrl=MonitorConfig.SERVER_ADDRESS+"/monitor_login";
                try {
                    param.put("deviceId",MonitorConfig.ANDROID_ID);
                    param.put("password",password);
                    param.put("bluetooth_mac",MonitorConfig.BLUETOOTH_MAC);
                    JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST,loginUrl,param,
                            response -> {
                                switch (response.optInt("code")){
                                    case 0:
                                        MonitorConfig.PASSWORD=password;
                                        ipPreferences.edit().putString("password",password).apply();
                                        if (response.optString("random").equals("")){
                                            Toast.makeText(this, "获取数据异常", Toast.LENGTH_SHORT).show();
                                            return;
                                        }
                                        MonitorConfig.RANDOM=response.optString("random");
                                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
                                        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                                        finish();
                                        break;
                                    default:
                                        Toast.makeText(this, "登录失败，请联系管理员处理", Toast.LENGTH_SHORT).show();
                                        break;
                                }
                            },error -> Toast.makeText(this, "网络错误 "+error.getMessage(), Toast.LENGTH_SHORT).show());
                    queue.add(jsonObjectRequest);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
    /*申请手机权限，在oncreate()方法中调用*/
    public void requestPermissions(){
        String [] permissions = new String[]{
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
        };
        //判断Android版本是否大于等于6.0
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            Log.e("requestPermission","申请权限");
            //申请权限，这时会弹出提示授权，如果已经授权，则不会弹出
            requestPermissions(permissions,2);
        }else{
            Log.e("requestPermission","已获得权限");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==2){
            if (permissions.length==0){
                Toast.makeText(this, "运行异常：无法获取权限", Toast.LENGTH_SHORT).show();
                return;
            }
            if (grantResults[0]!= PackageManager.PERMISSION_GRANTED||
                    grantResults[1]!= PackageManager.PERMISSION_GRANTED||
                    grantResults[2]!= PackageManager.PERMISSION_GRANTED||
                    grantResults[3]!= PackageManager.PERMISSION_GRANTED){
                new AlertDialog.Builder(this)
                        .setMessage("您拒绝授权，将无法使用部分功能")
                        .setPositiveButton("重新授权", (dialog, which) -> requestPermissions())
                        .setNegativeButton("关闭",null)
                        .show();
            }
        }
    }
    private void initData(){
        MonitorConfig.setAddress(ipPreferences.getString("ip",""),
                ipPreferences.getString("port",""));
        if (bluetoothAdapter==null){
            Toast.makeText(this, "该设备不支持蓝牙，无法使用本软件", Toast.LENGTH_SHORT).show();
            return;
        }
        String bluetoothMac=getBluetoothAddress();
        if (bluetoothMac==null||bluetoothMac.equals("")){
            Toast.makeText(this, "获取蓝牙地址失败，请尝试重新授权", Toast.LENGTH_SHORT).show();
        }else{
            ((TextView)findViewById(R.id.show_bluetooth_address)).setText("蓝牙地址："+bluetoothMac);
            MonitorConfig.BLUETOOTH_MAC=bluetoothMac;
        }
        String androidId = android.provider.Settings.Secure.getString(this.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);
        if (androidId.equals("")||androidId==null){
            Toast.makeText(this, "获取设备ID失败，请联系管理员处理", Toast.LENGTH_SHORT).show();
        }else{
            MonitorConfig.ANDROID_ID=androidId;
        }
        ((TextView)findViewById(R.id.edv_password)).setText(ipPreferences.getString("password",""));
    }

    private String getBluetoothAddress(){
        return
        android.provider.Settings.Secure.getString(this.getContentResolver(), "bluetooth_address");
        /*bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        try {
           Field field = BluetoothAdapter.class.getDeclaredField("mService");
            field.setAccessible(true);
            Object bluetoothManagerService = field.get(bluetoothAdapter);
            if (bluetoothManagerService == null) {
                return null;
            }
            Method method = bluetoothManagerService.getClass().getMethod("getAddress");
            if(method != null) {
                Object obj = method.invoke(bluetoothManagerService);
                if(obj != null) {
                    return obj.toString();
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;*/
    }
}